package jdbc.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.swing.JFileChooser;

public class ImagesToDB {
	Connection con = null;
	File fileDir = null;
	ImagesToDB(){
		MyFileChooser fc = new MyFileChooser();
		fc.setFileSelectionMode(MyFileChooser.DIRECTORIES_ONLY);
		fc.setDialogTitle("请选择文件夹");
		fc.setApproveButtonText("导入"); 
		fc.showOpenDialog(null);
		fileDir = fc.getSelectedFile();
		if(fileDir != null){
			try {
				Class.forName("com.mysql.jdbc.Driver");
				con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mytest","root","root");
				File[] imageArray = fileDir.listFiles();
				for(int i=0;i<imageArray.length;i++){
					File file = imageArray[i];
					String name = file.getName();
					FileInputStream fromFile = new FileInputStream(file);
					PreparedStatement pstm = con.prepareStatement("insert into images (name,image) values(?,?)");
					pstm.setString(1, name);
					pstm.setBinaryStream(2, fromFile, fromFile.available());
					pstm.execute();
					fromFile.close();
					pstm.close();
				}
				
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			finally{
				try {
					con.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}

	}
	public static void main(String[] args) {
		new ImagesToDB();
	}
}
class MyFileChooser extends JFileChooser{
	File selectedFile;
	public void approveSelection(){
		selectedFile = this.getSelectedFile();
		if(selectedFile != null){
			super.approveSelection();
		}
	}
	public void cancelSelection(){
		selectedFile = null;
		this.setSelectedFile(null);
		super.approveSelection();
	}
}